package com.kgc.storeprovider.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.kgc.basic.pojo.Good;
import com.kgc.basic.util.PageInfo;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.store.pojo.CostAdjustDetail;
import com.kgc.store.pojo.CostAdjustment;
import com.kgc.storeprovider.dao.CostAdjustmentMapper;
import com.kgc.storeprovider.service.CostAdjustmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Transactional
public class CostAdjustmentServiceImpl implements CostAdjustmentService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CostAdjustmentMapper costAdjustmentMapper;

    @Override
    public ResponseMsg selectByPage(Map<String, Object> map) {
        logger.info("CostAdjustmentServiceImpl selectByPage map={}", map);
        ResponseMsg responseMsg = new ResponseMsg();
        PageHelper.startPage(Integer.parseInt(map.get("pageNow").toString()), Integer.parseInt(map.get("pageSize").toString()));
        List<CostAdjustment> list = costAdjustmentMapper.getAllCostAdjustment(map);
        logger.debug("costAdjustmentMapper getAllCostAdjustment list:{}", list+",map"+map);
        PageHelper.clearPage();
        PageInfo<CostAdjustment> pageInfo = new PageInfo<>();
        if(list!=null&& !list.isEmpty()){
            pageInfo.setList(list);
            pageInfo.setPageNo(Integer.parseInt(map.get("pageNow").toString()));
            pageInfo.setPageSize(Integer.parseInt(map.get("pageSize").toString()));
            pageInfo.setTotal(costAdjustmentMapper.getCostAdjustmentCount(map));
        }
        if(pageInfo.getList()!=null&&pageInfo.getList().size()>0){
            responseMsg.setCode("200");
            responseMsg.setData(pageInfo);
        }else {
            responseMsg.setCode("201");
        }
        return responseMsg;
    }

    @Override
    public ResponseMsg selectByCode(String code) {
        logger.info("CostAdjustmentServiceImpl selectByCode code={}", code);
        ResponseMsg responseMsg = new ResponseMsg();
        CostAdjustment costAdjustment = costAdjustmentMapper.selectByCode(code);
        logger.debug("costAdjustmentMapper getCostAdjustment costAdjustment:{}", costAdjustment+",code"+code);
        if(costAdjustment!=null){
            responseMsg.setCode("200");
            responseMsg.setData(costAdjustment);
        }else {
            responseMsg.setCode("201");
        }
        return responseMsg;
    }

    @Override
    public ResponseMsg update(CostAdjustment costAdjustment) {
        logger.info("CostAdjustmentServiceImpl update costAdjustment:{}", costAdjustment);
        ResponseMsg responseMsg = new ResponseMsg();
        costAdjustment.setStatus(1);
        costAdjustment.setUpdateDate(new Date());
//        costAdjustment.setUpdateUser("1111");
        int count = costAdjustmentMapper.updateCostAdjustment(costAdjustment);
        logger.debug("costAdjustmentMapper updateCostAdjustment count:{}", count+",costAdjustment"+costAdjustment);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code",costAdjustment.getCode());
        List<Good> list = costAdjustment.getGoods();
        List<BigDecimal> numList = costAdjustment.getCounts();
        int num = costAdjustmentMapper.delDetail(map);
        logger.debug("costAdjustmentMapper delDetail num:{}", num+",map"+map);
        if (num==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        for (int i=0;i<list.size();i++){
            Good good = list.get(i);
            map.put("gid",good.getId());
            BigDecimal changeNum = numList.get(i);
            map.put("changeNum",changeNum);
            int nu = costAdjustmentMapper.addDetail(map);
            logger.debug("costAdjustmentMapper addDetail count:{}", nu+",map"+map);
            if(nu==0){
                responseMsg.setCode("201");
                return responseMsg;
            }
        }
        responseMsg.setCode("200");
        return responseMsg;
    }

    @Override
    public ResponseMsg add(CostAdjustment costAdjustment) {
        logger.info("CostAdjustmentServiceImpl add costAdjustment:{}", costAdjustment);
        ResponseMsg responseMsg = new ResponseMsg();
        costAdjustment.setStatus(1);
        costAdjustment.setCreateDate(new Date());
//        costAdjustment.setCreateUser("admin");
        costAdjustment.setUpdateDate(new Date());
//        costAdjustment.setUpdateUser("admin");
        int count = costAdjustmentMapper.addCostAdjustment(costAdjustment);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code",costAdjustment.getCode());
        List<Good> list = costAdjustment.getGoods();
        List<BigDecimal> numList = costAdjustment.getCounts();
        for (int i=0;i<list.size();i++){
            Good good = list.get(i);
            map.put("gid",good.getId());
            BigDecimal changeNum = numList.get(i);
            map.put("changeNum",changeNum);
            int num = costAdjustmentMapper.addDetail(map);
            logger.debug("costAdjustmentMapper addDetail num:{}",num+",map"+map);
            if(num==0){
                responseMsg.setCode("201");
                return responseMsg;
            }
        }
        responseMsg.setCode("200");
        return responseMsg;
    }

    @Override
    public ResponseMsg del(String code) {
        logger.info("CostAdjustmentServiceImpl del code:{}", code);
        ResponseMsg responseMsg = new ResponseMsg();
        int count = costAdjustmentMapper.delCostAdjustment(code);
        logger.debug("costAdjustmentMapper delCostAdjustment count:{}", count+",code"+code);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        count = costAdjustmentMapper.deleteDetail(code);
        logger.debug("costAdjustmentMapper deleteDetail count:{}", count+",code"+code);
        if(count==0){
            responseMsg.setCode("201");
            return responseMsg;
        }
        responseMsg.setCode("200");
        return responseMsg;
    }

    @Override
    public ResponseMsg insert(Map<String, Object> map) {
        logger.info("CostAdjustmentServiceImpl insert costAdjustment:{}", map);
        ResponseMsg msg = new ResponseMsg();
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 转换 SalesInvoice 对象
            CostAdjustment costAdjustment = mapper.convertValue(map.get("costAdjustment"), CostAdjustment.class);
            List<?> rawDetails = (List<?>) map.get("details");
            List<CostAdjustDetail> details = mapper.convertValue(rawDetails, new TypeReference<List<CostAdjustDetail>>() {
            });
            costAdjustment.setDate(new Date());
            // 设置时间字段
            costAdjustment.setCreateDate(new Date());
            costAdjustment.setUpdateDate(new Date());
            // 插入主表
            int result = costAdjustmentMapper.addCostAdjustment(costAdjustment);
            if (result <= 0) {
                msg.setCode("301");
                msg.setMsg("新增成本调整失败");
                return msg;
            }

            // 插入明细表
            for (CostAdjustDetail detail : details) {
                detail.setCreateDate(new Date());
                detail.setUpdateDate(new Date());
                detail.setCreateUser("admin");
                detail.setUpdateUser("admin");
                detail.setIsDelete(0);
                costAdjustmentMapper.insertDetail(detail);
            }

            msg.setCode("200");
            msg.setMsg("新增成本调整成功");
        } catch (Exception e) {
            logger.error("SalesInvoiceServiceImpl insertSalesInvoice error", e);
            msg.setCode("500");
            msg.setMsg("新增成本调整失败: " + e.getMessage());
            throw new RuntimeException("新增销售发票失败", e); // 抛出异常以触发事务回滚
        }

        logger.debug("SalesInvoiceServiceImpl insertSalesInvoice result:{}", msg);
        return msg;
    }

    @Override
    public ResponseMsg changePrice(CostAdjustment costAdjustment) {
        logger.info("CostAdjustmentServiceImpl changePrice costAdjustment:{}", costAdjustment);
        ResponseMsg msg = new ResponseMsg();
        List<Good> list = costAdjustment.getGoods();
        List<BigDecimal> numList = costAdjustment.getCounts();
        Map<String,Object> map = new HashMap<>();
        for(int i=0;i<list.size();i++){
            map.put("gid",list.get(i).getId());
            map.put("changeNum",numList.get(i));
            int num = costAdjustmentMapper.changPrice(map);
            logger.debug("costAdjustmentMapper changPrice:{}",num+",map"+map);
            if(num<1){
                msg.setCode("201");
                return msg;
            }
        }
        msg.setCode("200");
        return msg;
    }
}
